package com.hckj.jianzhijia.services;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Message;
import android.os.Parcelable;
import android.widget.RemoteViews;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.GetDataCallback;
import com.avos.avoscloud.ProgressCallback;
import com.hckj.jianzhijia.JianzhijiaApplacation;
import com.hckj.jianzhijia.MainActivity;
import com.hckj.jianzhijia.R;
import com.hckj.jianzhijia.utils.Data;
import com.hckj.jianzhijia.utils.ExceptionUtils;
import com.hckj.jianzhijia.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Handler;


public class APKLoadingService extends IntentService {

    private static final String ACTION_LOADING_APK = "com.hckj.jianzhijia.services.action.loadingAPK";
    private static final String URL = "com.hckj.jianzhijia.services.extra.URL";
    private static final int NOTIFICATION_ID = 1;
    private static final int ON_DOWNLOADING = 1;
    private static final int DOWNLOAD_FINISH = 2;
    private static final int SD_CARD_ERROR = 3;
    private static final int NET_ERROR = 4;
    private static final int OTHER_ERROR = 5;

    private String mSavePath = Data.sdpath + "download/";
    private String loadingUrl;

    private NotificationManager nm;
    private Notification notification;
    private Notification.Builder builder;
    private CountDownTimer countDownTimer;
    private int progress = 0;

    private android.os.Handler loadingHander = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case ON_DOWNLOADING:
                    showNotification();
                    countDownTimer =  new CountDownTimer(600000,1500){
                        @Override
                        public void onFinish() {
                            loadingHander.sendEmptyMessage(NET_ERROR);
                        }

                        @Override
                        public void onTick(long millisUntilFinished) {
                            builder.setNumber(progress);
                            builder.setProgress(100,progress,false);
                            nm.notify(NOTIFICATION_ID, builder.getNotification());
                        }
                    };
                    countDownTimer.start();
                    break;
                case DOWNLOAD_FINISH:
                    builder.setNumber(100);
                    builder.setProgress(100, 100, false);
                    builder.setContentTitle("兼职家下载完成");
                    notification =  builder.getNotification();
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;
                    nm.notify(NOTIFICATION_ID,notification);
                    countDownTimer.cancel();
                    break;
                case SD_CARD_ERROR:
                    ToastUtils.showToast(getApplicationContext(), "无法读取SD卡");
                    break;
                case NET_ERROR:
                    ToastUtils.showToast(getApplicationContext(), "下载超时");
                    countDownTimer.cancel();
                    nm.cancel(NOTIFICATION_ID);
                    //todo 通过浏览器手动更新
                    break;
                case OTHER_ERROR:
                    ToastUtils.showToast(getApplicationContext(), "未知错误");
                    countDownTimer.cancel();
                    nm.cancel(NOTIFICATION_ID);
                    break;
            }

        }
    };


    public APKLoadingService() {
        super("APKLoadingService");
    }

    public static void startUpdate(Context context, String loadingUrl) {
        Intent intent = new Intent(context, APKLoadingService.class);
        intent.putExtra(URL, loadingUrl);
        intent.setAction(ACTION_LOADING_APK);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_LOADING_APK.equals(action)) {
                loadingUrl = intent.getStringExtra(URL);
                try {
                    loadingAPK();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                return;
            }
        }
    }


    private void loadingAPK(){
        DownLoadNetTask downLoadNetTask = new DownLoadNetTask();
        downLoadNetTask.execute();
    }

    private void installApk() {
        File apkfile = new File(mSavePath, "jianzhijia.apk");
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        APKLoadingService.this.startActivity(i);
    }


    private void showNotification() {
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        builder = new Notification.Builder(this)
                              .setSmallIcon(R.mipmap.ic_launcher)
                              .setContentTitle("兼职家更新中...")
                              .setProgress(100, 0, false)
                              .setNumber(0);
        notification = builder.getNotification();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        nm.notify(NOTIFICATION_ID, notification);
    }


    class DownLoadNetTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                loadingHander.sendEmptyMessage(ON_DOWNLOADING);
                try {
                    java.net.URL url = new URL(loadingUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();
                    File file = new File(mSavePath + "jianzhijia.apk");
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                    final FileOutputStream fos = new FileOutputStream(file);
                    int count = 0;
                    byte buf[] = new byte[1024];
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        if (numread <= 0) {
                            loadingHander.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (true);// 点击取消就停止下载.
                    fos.close();
                    is.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    loadingHander.sendEmptyMessage(OTHER_ERROR);
                }
                installApk();
            } else {
                loadingHander.sendEmptyMessage(SD_CARD_ERROR);
            }
            return null;
        }
    }
}
